var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
require('./db');
var jwt = require('express-jwt');  // 引入jwt模块
var { secretKey, unless, algorithms } = require('./utils/token'); // 引入自定义配置信息
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');//用户管理
var servicesRouter = require('./routes/services');// 服务管理
var shopsRouter = require('./routes/shops');// 店铺模块
var adminRouter = require('./routes/admin');// 管理员模块
var orderGoodsRouter = require('./routes/orderGoods');  // 订单商品
var orderServicesRouter = require('./routes/orderServices');  // 订单服务
var applyRouter = require('./routes/apply');  //申请模块
var goodsRouter = require('./routes/goods');  //商品模块
var addressesRouter = require('./routes/addresses');  //地址模块



var app = express();
// 配置jwt的密钥、加密算法，以及不需要认证的路径，下面代码一定要放在var app = express();的后面
app.use(jwt({ secret: secretKey, algorithms }).unless(unless));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/services', servicesRouter);// 服务管理
app.use('/shops', shopsRouter);// 店铺管理
app.use('/orderGoods', orderGoodsRouter);  // 订单商品
app.use('/orderServices', orderServicesRouter);  // 订单服务
app.use('/apply', applyRouter);  // 申请模块
app.use('/goods', goodsRouter);  // 商品模块
app.use('/admin', adminRouter);  // 管理员模块
app.use('/addresses', addressesRouter);  // 地址模块

app.use(session({
  secret: "sonder",
  resave: false, // 强制保存session，默认为true，即使它没有变化，建议false
  saveUninitialized: true // 强制将未初始化的session存储（当新建一个sesison，但未设定属性和值时处于未初始化状态）
}));

app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
   // 如果认证失败返回401状态和invalid token字符串
   if (err.name === "UnauthorizedError") {
    res.status(401).send("invalid token");
  }else{
    // render the error page
    res.status(err.status || 500);
    console.log("error:",err.message);
    res.render('error');
  }
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
